package com.irononetech.android.formcomponent.view;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import com.irononetech.android.Application.Application;
import com.irononetech.android.Webservice.URL;
import com.irononetech.android.claimsonersa.R;
import com.irononetech.android.fileio.FileOperations;
import com.irononetech.android.formcomponent.FormObject;
import com.irononetech.android.formcomponent.VisitObject;
import com.irononetech.android.utilities.JPGFileFilter;

public class CustomGalleryJobDocsAdd extends Activity {
	Logger LOG = LoggerFactory.getLogger(CustomGalleryJobDocsAdd.class);
	private int count;
	// private Bitmap[] thumbnails;
	private boolean[] thumbnailsselection;
	private String[] arrPath;
	private ImageAdapter imageAdapter;
	//Bundle extras;
	Intent extras;
	/** Called when the activity is first created. */

	List<File> finalFileList;
	ArrayList<String> selectedFileList;
	ProgressDialog progressDialog;

	public void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			LOG.debug("ENTRY onCreate");
			setContentView(R.layout.imagegallerymain);

			extras = this.getIntent(); //.getExtras();
			
			new SelectAsyncTask().execute();
			progressDialog = ProgressDialog.show(this, "", "Loading...", true);

			// imagecursor.close();

			final Button selectBtn = (Button) findViewById(R.id.selectBtn);
			selectBtn.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					LOG.debug("ENTRY ", "selectBtn-onClick");
					final int len = thumbnailsselection.length;
					// int cnt = 0;
					String selectImages = "";
					for (int i = 0; i < len; i++) {
						if (thumbnailsselection[i]) {
							// cnt++;
							selectImages = selectImages + arrPath[i] + "|";
							selectedFileList.add(arrPath[i]);
						}
					}

					// if (cnt == 0){
					// Toast.makeText(getApplicationContext(),
					// "Please select at least one image",
					// Toast.LENGTH_LONG).show();
					// } else {
					// Toast.makeText(getApplicationContext(),
					// "You've selected Total " + cnt + " image(s).",
					// Toast.LENGTH_LONG).show();
					// Log.d("SelectedImages", selectImages);
					// }

					// Suren
					// identify the image category
					String foldername = "";
					boolean isVisit = Application.getIsVisit();
					if (extras != null) {
						foldername = extras.getStringExtra("SELECTION_ID");
						//isVisit = extras.getBooleanExtra("ISVISIT", false);
					}

					String destinationFolder = "";

					if (!isVisit) { // SA Form
						// SLIC Code
						FormObject formObject = Application.getFormObjectInstance();

						if (foldername.equals("DLStatement")) {
							formObject.setselectedDLStatementImages(thumbnailsselection);
						}
						if (foldername.equals("TechnicalOfficerComments")) {
							formObject.setselectedTechnicalOfficerCommentsImages(thumbnailsselection);
						}
						if (foldername.equals("ClaimFormImage")) {
							formObject.setselectedClaimFormImageImages(thumbnailsselection);
						}
						if (foldername.equals("ARI")) {
							formObject.setselectedARIImages(thumbnailsselection);
						}
						if (foldername.equals("DR")) {
							formObject.setselectedDRImages(thumbnailsselection);
						}
						if (foldername.equals("SeenVisit")) {
							formObject.setselectedSeenVisitImages(thumbnailsselection);
						}
						if (foldername.equals("SpecialReport1")) {
							formObject.setselectedSpecialReport1Images(thumbnailsselection);
						}
						if (foldername.equals("SpecialReport2")) {
							formObject.setselectedSpecialReport2Images(thumbnailsselection);
						}
						if (foldername.equals("SpecialReport3")) {
							formObject.setselectedSpecialReport3Images(thumbnailsselection);
						}
						if (foldername.equals("Supplementary1")) {
							formObject.setselectedSupplementary1Images(thumbnailsselection);
						}
						if (foldername.equals("Supplementary2")) {
							formObject.setselectedSupplementary2Images(thumbnailsselection);
						}
						if (foldername.equals("Supplementary3")) {
							formObject.setselectedSupplementary3Images(thumbnailsselection);
						}
						if (foldername.equals("Supplementary4")) {
							formObject.setselectedSupplementary4Images(thumbnailsselection);
						}
						if (foldername.equals("Acknowledgment")) {
							formObject.setselectedAcknowledgmentImages(thumbnailsselection);
						}
						if (foldername.equals("SalvageReport")) {
							formObject.setselectedSalvageReportImages(thumbnailsselection);
						}

						destinationFolder = formObject.getJobNo();

					} else {
						VisitObject VisitObject = Application.getVisitObjectInstance();

						if (foldername.equals("TechnicalOfficerComments")) {
							VisitObject.setselectedTechnicalOfficerCommentsImages(thumbnailsselection);
						}
						if (foldername.equals("EstimateAnyotherComments")) {
							VisitObject.setselectedEstimateAnyotherComments(thumbnailsselection);
						}
						if (foldername.equals("InspectionPhotosSeenVisitsAnyOther")) {
							VisitObject.setselectedInspectionPhotosSeenVisitsAnyOther(thumbnailsselection);
						}

						destinationFolder = VisitObject.getVisitFolderName();
					}

					if (!destinationFolder.equals("")) {
						if(!isVisit)
							FileOperations.copyFilesFromDirToDirAddDocs(selectedFileList, destinationFolder	+ "/DocImages/" + foldername);
						else
							FileOperations.copyFilesFromDirToDirAddDocsForVisits(selectedFileList, destinationFolder + "/DocImages/" + foldername);
					}
					/*else {
						new AlertDialog.Builder(CustomGalleryJobDocsAdd.this)
						.setTitle(R.string.alert_dialog_two_buttons_title)
						.setPositiveButton(R.string.alert_dialog_ok,
								new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,	int whichButton) {
							}
						})
						.setNegativeButton(R.string.alert_dialog_cancel,
								new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,	int whichButton) {
							}
						}).create();
					}*/
					finish();

					LOG.debug("SUCCESS ","selectBtn-onClick");
					
				}
			});
			Toast.makeText(this, "long click the thumbnails to view", Toast.LENGTH_LONG).show();
			
			LOG.debug("onClick");
		} catch (Exception e) {
			LOG.error("onCreate:10441");
			   if(e != null){
				LOG.error("Message: " + e.getMessage());
				LOG.error("StackTrace: " + e.getStackTrace());
			  }
		}
	}
	
	private class SelectAsyncTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPostExecute(Void result) {
			try {
				selectedFileList = new ArrayList<String>();

				// final String[] columns = { MediaStore.Images.Media.DATA,
				// MediaStore.Images.Media._ID };
				// final String orderBy = MediaStore.Images.Media._ID;
				// Cursor imagecursor = managedQuery(
				// MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
				// null, orderBy);
				// int image_column_index =
				// imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
				// this.count = imagecursor.getCount();

				count = finalFileList.size();
				// this.thumbnails = new Bitmap[this.count];
				arrPath = new String[count];
				thumbnailsselection = new boolean[count];

				boolean[] arr = null;
				String foldername = "";
				boolean isVisit = Application.getIsVisit();
				
				if (extras != null) {
					foldername = extras.getStringExtra("SELECTION_ID");
				}

				if (!isVisit) { // SA Form
					FormObject formObject = Application.getFormObjectInstance();
					if (foldername.equals("DLStatement")) {
						arr = formObject.getselectedDLStatementImages();
					}
					if (foldername.equals("TechnicalOfficerComments")) {
						arr = formObject.getselectedTechnicalOfficerCommentsImages();
					}
					if (foldername.equals("ClaimFormImage")) {
						arr = formObject.getselectedClaimFormImageImages();
					}
					if (foldername.equals("ARI")) {
						arr = formObject.getselectedARIImages();
					}
					if (foldername.equals("DR")) {
						arr = formObject.getselectedDRImages();
					}
					if (foldername.equals("SeenVisit")) {
						arr = formObject.getselectedSeenVisitImages();
					}
					if (foldername.equals("SpecialReport1")) {
						arr = formObject.getselectedSpecialReport1Images();
					}
					if (foldername.equals("SpecialReport2")) {
						arr = formObject.getselectedSpecialReport2Images();
					}
					if (foldername.equals("SpecialReport3")) {
						arr = formObject.getselectedSpecialReport3Images();
					}
					if (foldername.equals("Supplementary1")) {
						arr = formObject.getselectedSupplementary1Images();
					}
					if (foldername.equals("Supplementary2")) {
						arr = formObject.getselectedSupplementary2Images();
					}
					if (foldername.equals("Supplementary3")) {
						arr = formObject.getselectedSupplementary3Images();
					}
					if (foldername.equals("Supplementary4")) {
						arr = formObject.getselectedSupplementary4Images();
					}
					if (foldername.equals("Acknowledgment")) {
						arr = formObject.getselectedAcknowledgmentImages();
					}
					if (foldername.equals("SalvageReport")) {
						arr = formObject.getselectedSalvageReportImages();
					}
				} else {
					VisitObject visitObject = Application.getVisitObjectInstance();

					if (foldername.equals("TechnicalOfficerComments")) {
						arr = visitObject.getselectedTechnicalOfficerCommentsImages();
					}
					if (foldername.equals("EstimateAnyotherComments")) {
						arr = visitObject.getselectedEstimateAnyotherComments();
					}
					if (foldername.equals("InspectionPhotosSeenVisitsAnyOther")) {
						arr = visitObject.getselectedInspectionPhotosSeenVisitsAnyOther();
					}
				}

				if (thumbnailsselection != null && arr != null) {
					for (int i = 0; i < thumbnailsselection.length; i++) {
											
						/* Need this condition on a situation where user select few images
						 * and then copy more images to Copied folder.
						 * Without this condition user gets an empty page with no images to select.
						 * */
						if(i < arr.length)
							thumbnailsselection[i] = arr[i];
						else
							break;
					}
				}

				for (int i = 0; i < count; i++) {
					// imagecursor.moveToPosition(i);
					// int id = imagecursor.getInt(image_column_index);
					// int dataColumnIndex =
					// imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
					// thumbnails[i] =
					// MediaStore.Images.Thumbnails.getThumbnail(
					// getApplicationContext().getContentResolver(), id,
					// MediaStore.Images.Thumbnails.MICRO_KIND, null);
					// arrPath[i]= imagecursor.getString(dataColumnIndex);

					arrPath[i] = finalFileList.get(i).toString();
				}
				
				GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
				imageAdapter = new ImageAdapter();
				imagegrid.setAdapter(imageAdapter);

				progressDialog.dismiss();
				super.onPostExecute(result);
			} catch (Exception e) {
				progressDialog.dismiss();
				LOG.error("onPostExecute:10439");
				   if(e != null){
					LOG.error("Message: " + e.getMessage());
					LOG.error("StackTrace: " + e.getStackTrace());
				  }
			}
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				finalFileList = imageList();
			} catch (Exception e) {
				LOG.error("doInBackground:10440");
				   if(e != null){
					LOG.error("Message: " + e.getMessage());
					LOG.error("StackTrace: " + e.getStackTrace());
				  }
			}
			return null;
		}
	}

	public class ImageAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		public ImageAdapter() {
			mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public int getCount() {
			// return count;
			return finalFileList.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			
			try {
				ViewHolder holder;
				
				if (convertView == null) {
					holder = new ViewHolder();
					convertView = mInflater.inflate(R.layout.galleryitem, null);
					holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
					holder.checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);
					convertView.setTag(holder);
				} else {
					holder = (ViewHolder) convertView.getTag();
				}
				final ViewHolder holder1 = holder;
				holder.checkbox.setId(position);
				holder.checkbox.setChecked(thumbnailsselection[position]);
				holder.imageview.setId(position);
				holder.checkbox.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						CheckBox cb = (CheckBox) v;
						int id = cb.getId();
						if (thumbnailsselection[id]) {
							cb.setChecked(false);
							thumbnailsselection[id] = false;
						} else {
							cb.setChecked(true);
							thumbnailsselection[id] = true;
						}
					}
				});
				holder.imageview.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {												
						CheckBox cb = (CheckBox)holder1.checkbox;
						int id = cb.getId();
						if (thumbnailsselection[id]) {
							cb.setChecked(false);
							thumbnailsselection[id] = false;
						} else {
							cb.setChecked(true);
							thumbnailsselection[id] = true;
						}						
					}
				});
				holder.imageview.setOnLongClickListener(new OnLongClickListener() {
					@Override
					public boolean onLongClick(View v) {
						try {
							// Removed due to high memory consumption (3MB >
							// images will generate an exception)
							/*
							 * Intent mIntent = new
							 * Intent(CustomGalleryJobDocsAdd.this,
							 * PopupImage.class);
							 * mIntent.putExtra("selectedImage",
							 * arrPath[v.getId()]); startActivity(mIntent);
							 */
							Intent intent = new Intent();
							intent.setAction(Intent.ACTION_VIEW);
							intent.setDataAndType(Uri.parse("file://" + arrPath[v.getId()]), "image/*");
							startActivity(intent);
						} catch (Exception e) {
							LOG.error("onClick");
							   if(e != null){
								LOG.error("Message: " + e.getMessage());
								LOG.error("StackTrace: " + e.getStackTrace());
							  }
						}
						return false;
					}
				});
				
				// ImageView imageView = new ImageView(mContext);
				// Bitmap bitmapImage =
				// BitmapFactory.decodeFile(finalFileList.get(position).toString());
				Bitmap bitmapImage = FileOperations.ShrinkBitmap(finalFileList
						.get(position).toString(), 150, 200);

				BitmapDrawable drawableImage = new BitmapDrawable(bitmapImage);
				// imageView.setImageDrawable(drawableImage );
				holder.imageview.setImageDrawable(drawableImage);
				// holder.imageview.setImageBitmap(thumbnails[position]);
				holder.checkbox.setChecked(thumbnailsselection[position]);
				holder.id = position;
				return convertView;
			} catch (Exception e) {
				LOG.error("getView:10442");
				   if(e != null){
					LOG.error("Message: " + e.getMessage());
					LOG.error("StackTrace: " + e.getStackTrace());
				  }
				return null;
			}
		}
	}

	public List<File> imageList() {

		/*
		 * File myDirectory = new
		 * File(Environment.getExternalStorageDirectory(), "mydirectory");
		 * if(!myDirectory.exists()) { myDirectory.mkdirs(); }
		 */
		// File a = Environment.getExternalStorageDirectory();
		File f = new File(URL.getSLIC_COPIED());
		// File f = new File("/Root/DICM/Camera");
		List<File> fileList = FileOperations.listFiles(f, new JPGFileFilter(),
				true);

		/*String fileNames = "";
		for (int i = 0; i < fileList.size(); i++) {
			fileNames += ">>" + fileList.get(i).getPath() + "\n";
		}*/
		return fileList;
		// tv.setText(fileNames);
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			//return false;
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	public void on_click_back_button(View v){
		finish();
	}
}
